﻿#region Copyright (C) Sector7 Software Studio. All rights reserved
/*******************************************************************************************
 * Creation
 *      Author:         Wolf Lai
 *      Date:           2011/10/27 22:11:41
 *      Version:        1.0.1101
 * Modification 
 *      Author: 
 *      Date: 
 *      Description: 
 *      Version:
 *******************************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Sector7.Framework.Enums;
using Sector7.Framework.Core;
using Sector7.Framework.Consts;

namespace Sector7.Framework.Utility
{
    /// <summary>
    /// Socket工具类
    /// </summary>
    public class SocketUtil
    {
        #region Public functions
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="socket">套接字对象</param>
        /// <param name="length">接收数据长度</param>
        /// <returns>接收失败返回长度为0数组</returns>
        public static byte[] ReceiveData(Socket socket, int length)
        {
            return ReceiveData(socket, length, true);
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="socket">套接字对象</param>
        /// <param name="length">接收数据长度</param>
        /// <param name="isCareLength">是否关心长度</param>
        /// <returns></returns>
        public static byte[] ReceiveData(Socket socket, int length, bool isCareLength)
        {
            int receivedLength = 0;
            int index = 0;
            byte[] data = new byte[length];

            do
            {
                byte[] tempData = new byte[length - receivedLength];
                int count = socket.Receive(tempData);

                if (count != 0)
                {
                    receivedLength += count;

                    for (int i = index; i < receivedLength; i++)
                    {
                        data[i] = tempData[i - index];
                    }

                    index = receivedLength;

                    if (!isCareLength)
                        break;
                }

                if (count == 0 && receivedLength != length)
                {
                    Log.WriteLine(LogSeverityType.WRN, C_ModuleName.FRAMEWORK, "Socket Receive Data's length is 0!");
                    return new byte[0] { };
                }
            } while (receivedLength != length);

            return data;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="socket">套接字对象</param>
        /// <param name="data">数据内容</param>
        public static void SendData(Socket socket, string data)
        {
            byte[] datas = StringUtil.StringToBytes(data);
            socket.Send(datas, datas.Length, 0);
        }
        #endregion
    }
}
